package com.common;

import com.alibaba.fastjson.JSON;
import com.pojo.dto.Message;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 通用异常处理器，该异常处理器负责拦截各种异常，具体使用时需要和@ExceptionHandler注解匹配
 * 用以拦截具体的异常，比如@ExceptionHandler(value = ServiceException.class)拦截ServiceException
 * 异常。
 */

public class CustomerExceptionResolver {

    @ExceptionHandler(value = AuthenticationException.class)
    @ResponseBody
    public String handle(AuthenticationException e) {
        Message<String> message = Message.errorMessage("100001", e.getMessage());
        return JSON.toJSONString(message);
    }

    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public String handle(ServiceException e) {
        Message<String> message = Message.errorMessage(e.getCode(), e.getMessage());
        return JSON.toJSONString(message);
    }

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public String handle(RuntimeException e) {
        Message<String> message = Message.errorMessage("500000", e.getMessage());
        return JSON.toJSONString(message);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String handle(Exception e) {
        Message<String> message = Message.errorMessage("600000", e.getMessage());
        return JSON.toJSONString(message);
    }
}
